package tools

import (
	"github.com/jinzhu/gorm"
	"github.com/sirupsen/logrus"
)

type Trans struct {
	db *gorm.DB
}

func New(db *gorm.DB) *Trans {
	return &Trans{db}
}

func (trans *Trans) View(f func(db *gorm.DB) error) error {
	err := f(trans.db)
	return err
}

// 封装事物处理
// 防止忘记commit或者rollback
func (trans *Trans) Update(f func(tx *gorm.DB) error) error {
	tx := trans.db.Begin()
	err := f(tx)
	if err != nil {
		tx.Rollback()
		logrus.WithError(err).Error("database rollback")
		return err
	}
	tx.Commit()
	return tx.Error
}
